//
//  VideoController.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/27.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "VideoController.h"
#import "HWLNetworkTool.h"
#import "videoMainModel.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "VideoTableViewCell.h"
#import "VideoPlayerViewController.h"
#import "MJRefresh.h"
#import "Reachability.h"

@interface VideoController ()

@property (nonatomic, strong) videoMainModel *mainData;
@property (nonatomic, retain) News_List *newsList;
@property (nonatomic, strong)videoMainModel *videoModel;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicatorView;

@end


@implementation VideoController

- (void)viewDidLoad{
    [self createactivityIndicatorView];
    [self createNavigationItem];
    [self handeledata];
    
    //指定tableview大小
    
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    
    [self.tableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:@"videoCell"];
    
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf handeledata];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
        [weakSelf handeledata];
    }];

}

- (void)createactivityIndicatorView{
    
    self.activityIndicatorView=[[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    self.activityIndicatorView.center=self.view.center;
    [self.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.activityIndicatorView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
}

- (void)createNavigationItem{
    
    
    //设置navigation相关属性
    
  
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.navigationItem.title = @"视频";
  

    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
}


- (void)handeledata{

    [self.activityIndicatorView stopAnimating];
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000;
    
    NSString *string = [NSString stringWithFormat:@"%lf",time];
   
    
    /*GET http://121.42.190.40/news_list/%E8%A7%86%E9%A2%91?count=20&ts=1473037979*/
    
    
    
    
    
    
    NSString *getRequest = [@"http://121.42.190.40/news_list/%E8%A7%86%E9%A2%91?count=20&ts="stringByAppendingString:string];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //离线缓存
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *cloudCaches = [documentPath stringByAppendingPathComponent:@"/default/com.hackemist.SDWebImageCache.default"];
    
    BOOL result = [fileManager createDirectoryAtPath:cloudCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (result == YES) {
        
    }else {
        
    }
    
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long)[getRequest hash]];
    
    NSString *TextFilePath = [cloudCaches stringByAppendingPathComponent:path];
    
    
    
    Reachability* reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    
    // Set the blocks
    reach.reachableBlock = ^(Reachability*reach)
    {
        // keep in mind this is called on a background thread
        // and if you are updating the UI it needs to happen
        // on the main thread, like this:
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"REACHABLE!");
        });
    };
    
    reach.unreachableBlock = ^(Reachability*reach)
    {
        NSLog(@"UNREACHABLE!");
        
        NSDictionary *dic1 = [NSKeyedUnarchiver unarchiveObjectWithFile:TextFilePath];
        
        self.videoModel = [videoMainModel modelWithDic:dic1];
        [self.tableView reloadData];

    };
    
    
    
    [manager GET:getRequest parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        self.videoModel = [videoMainModel modelWithDic:responseObject];
        
       // NSLog(@"%@",responseObject);
        
        
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        // 序列化（等同于将文件写入本地）
        BOOL result1 = [NSKeyedArchiver archiveRootObject:responseObject toFile:TextFilePath];
        if (result1) {
         //   NSLog(@"写入成功");
        }else {
           // NSLog(@"写入失败");
        }

        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSDictionary *dic1 = [NSKeyedUnarchiver unarchiveObjectWithFile:TextFilePath];
        
        self.videoModel = [videoMainModel modelWithDic:dic1];
        [self.tableView reloadData];

        
    }];

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{


    return self.videoModel.data.news_list.count;

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


    VideoTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"videoCell"];
    
    
    cell.labelOfTitle.text = self.videoModel.data.news_list[indexPath.row].title;
    
    cell.labelOfsource.text = self.videoModel.data.news_list[indexPath.row].source;
    
    
    NSString *str = self.videoModel.data.news_list[indexPath.row].thumb;
    
    NSURL *url = [NSURL URLWithString:str];
    
    [cell.imageViewOfthumb sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    return 100;

}


#pragma mark - 当前单元格被选中方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    VideoPlayerViewController *videoPlayerViewController = [[VideoPlayerViewController alloc]init];
     NSString *strOfVideo = self.videoModel.data.news_list[indexPath.row].source_url;
     videoPlayerViewController.urlOfVideo = [NSURL URLWithString:strOfVideo];
    
    
    [self.navigationController pushViewController:videoPlayerViewController animated:YES];




}













@end
